<template>
  <div class="detail-container">
    <el-card v-if="testDetail">
      <template #header>
        <div class="card-header">
          <h2>测试详情</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>
      
      <div class="test-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="测试URL">{{ testDetail.url }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDate(testDetail.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="测试时长">{{ testDetail.duration }}秒</el-descriptions-item>
          <el-descriptions-item label="并发用户数">{{ testDetail.concurrentUsers }}</el-descriptions-item>
          <el-descriptions-item label="总请求数">{{ testDetail.totalRequests }}</el-descriptions-item>
          <el-descriptions-item label="成功率">
            <el-progress 
              :percentage="testDetail.successRate" 
              :status="testDetail.successRate >= 90 ? 'success' : 'exception'"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div class="charts-section">
        <div class="chart-container">
          <div ref="responseTimeChart" style="width: 100%; height: 300px;"></div>
        </div>
        <div class="chart-container">
          <div ref="requestsPerSecondChart" style="width: 100%; height: 300px;"></div>
        </div>
      </div>
      
      <div class="api-stats">
        <h3>接口统计</h3>
        <el-table :data="testDetail.apiStats" style="width: 100%">
          <el-table-column prop="endpoint" label="接口" show-overflow-tooltip />
          <el-table-column prop="totalRequests" label="请求数" width="120" />
          <el-table-column prop="successRequests" label="成功数" width="120" />
          <el-table-column prop="failedRequests" label="失败数" width="120" />
          <el-table-column prop="avgResponseTime" label="平均响应时间" width="150">
            <template #default="scope">
              {{ scope.row.avgResponseTime }}ms
            </template>
          </el-table-column>
          <el-table-column prop="minResponseTime" label="最小响应时间" width="150">
            <template #default="scope">
              {{ scope.row.minResponseTime }}ms
            </template>
          </el-table-column>
          <el-table-column prop="maxResponseTime" label="最大响应时间" width="150">
            <template #default="scope">
              {{ scope.row.maxResponseTime }}ms
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-empty v-else description="未找到测试记录" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useTestStore } from '../stores/test'
import * as echarts from 'echarts'

const route = useRoute()
const router = useRouter()
const testStore = useTestStore()

const responseTimeChart = ref(null)
const requestsPerSecondChart = ref(null)
let charts = []

const testDetail = computed(() => {
  const id = parseInt(route.params.id)
  return testStore.getTestById(id)
})

const formatDate = (date) => {
  return new Date(date).toLocaleString()
}

const initCharts = () => {
  if (!testDetail.value?.apiStats?.length) return

  const apiStats = testDetail.value.apiStats[0]
  const responseTimes = apiStats.responseTimes || []
  const timePoints = responseTimes.map(item => item.time)
  
  // 计算每秒请求数
  const requestsPerSecond = []
  if (timePoints.length > 1) {
    const interval = 1000 // 1秒
    let currentTime = timePoints[0]
    const endTime = timePoints[timePoints.length - 1]
    
    while (currentTime <= endTime) {
      const nextTime = currentTime + interval
      const count = responseTimes.filter(
        item => item.time >= currentTime && item.time < nextTime
      ).length
      requestsPerSecond.push([currentTime, count])
      currentTime = nextTime
    }
  }

  // 响应时间趋势图
  const responseTimeChartInstance = echarts.init(responseTimeChart.value)
  responseTimeChartInstance.setOption({
    title: {
      text: '响应时间趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '响应时间(ms)',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '响应时间',
      type: 'line',
      smooth: true,
      data: responseTimes.map(item => [item.time, item.value])
    }]
  })
  
  // 每秒请求数趋势图
  const requestsPerSecondChartInstance = echarts.init(requestsPerSecondChart.value)
  requestsPerSecondChartInstance.setOption({
    title: {
      text: '每秒请求数'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'time',
      splitLine: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '请求数/秒',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '请求数',
      type: 'line',
      smooth: true,
      data: requestsPerSecond
    }]
  })
  
  charts = [responseTimeChartInstance, requestsPerSecondChartInstance]
}

onMounted(() => {
  if (!testDetail.value) {
    router.replace('/history')
    return
  }
  
  initCharts()
  window.addEventListener('resize', () => {
    charts.forEach(chart => chart?.resize())
  })
})

onUnmounted(() => {
  charts.forEach(chart => chart?.dispose())
  window.removeEventListener('resize', () => {
    charts.forEach(chart => chart?.resize())
  })
})
</script>

<style scoped>
.detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-info {
  margin-bottom: 30px;
}

.charts-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.chart-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.api-stats {
  margin-top: 30px;
}

.api-stats h3 {
  margin-bottom: 20px;
}
</style> 